<template>
  <div style="padding: 10px;">
    <div style="display:flex;flex-direction: row;justify-content: center;justify-items: center;">
      <lay-upload ref="uploadRef" :beforeUpload="beforeUpload" :drag="false" text="选择文件" :url='uploadUrl' v-model="file"
        field="file" @done="doneHandle">
        <template #preview>
          {{ file[0]?.name }}
        </template>
      </lay-upload>
      <lay-button :disabled="!dataSource.length" type="primary" @click="handleUpload"
        style="margin-left: 20px;">上传数据库</lay-button>
    </div>

    <lay-table :default-toolbar="defaultToolbars" :resize="true" :height="'65vh'" :columns="columns" :loading="loading"
      :data-source="dataSource" even>

      <template v-slot:toolbar>
        <lay-button @click="downloadTemplate" size="sm">下载模板</lay-button>
      </template>
    </lay-table>

  </div>
</template>

<script setup>
import { ref } from 'vue'
import { layer } from '@layui/layui-vue';
import api from '@/api';
import { API_BASE_URL } from '@/config';

const file = ref([]);
const uploadRef = ref(null)
const dataSource = ref([]);
const loading = ref(false)
const uploadUrl = API_BASE_URL + '/api/get/excel';

async function downloadTemplate() {
  // layer.msg('下载模板', { icon: 1, time: 3000 });
  // await api.post('api/downloadfile', {
  //   name: '资源上传模板.xls',
  // })

  try {
    // 使用GET请求（推荐用于下载）
    window.open(API_BASE_URL + `/api/downloadfile?name=${encodeURIComponent('资源上传模板.xlsx')}`, '_blank');
  } catch (error) {
    console.error('下载失败:', error);
    layer.msg('下载失败!', { icon: 2, time: 3000 });
  }
}



function beforeUpload() {
  loading.value = true
}

const doneHandle = (result) => {
  result = JSON.parse(result.data);
  console.log(result)

  if (result.code == 200) {
    dataSource.value = result.data
    loading.value = false
    layer.msg("数据获取成功，确认无误后请点击【上传数据库】完成数据导入！", { icon: 1, time: 3000 });
  } else {
    layer.msg(result.msg, { icon: 2, time: 3000 });
  }

};

const handleUpload = async () => {
  if (dataSource.value.length == 0) {
    layer.msg('数据为空，请先选择文件！', { icon: 2, time: 3000 });
    return
  }
  loading.value = true
  // layer.msg('正在上传数据...', { icon: 1, time: 3000 });
  await api.post('resource/import', {
    dataSource: dataSource.value,
  }).then((response) => {

    if (response.code === 200) {
      console.log(response)
      layer.msg(response.msg, { icon: 1, time: 1000 });

      dataSource.value = []
    } else {
      console.log(response.msg)
      layer.msg(response.msg, { icon: 2, time: 2000 });
    }
  })
  loading.value = false
}


const defaultToolbars = ["filter", "export",]

const columns = ref([
  { title: "省", key: "province", align: 'center', hide: true, ellipsisTooltip: true, },
  { title: "市", key: "city", align: 'center', ellipsisTooltip: true },
  { title: "区/县", key: "county", align: 'center', ellipsisTooltip: true, },
  { title: "乡/镇", key: "town", align: 'center', ellipsisTooltip: true, },
  { title: "村", key: "village", align: 'center', ellipsisTooltip: true, },
  { title: "植被生态区", key: "vegetation_ecological_zone", align: 'center', ellipsisTooltip: true, },
  { title: "生态工程区", key: "ecological_engineering_zone", align: 'center', ellipsisTooltip: true, },
  { title: "生态分区", key: "ecological_zone", align: 'center' },
  { title: "森林类别", key: "forest_class", align: 'center' },
  { title: "事权级", key: "forest_level", align: 'center' },
  { title: "生态分区2", key: "ecological_zone_2", align: 'center', hide: true, ellipsisTooltip: true, },
  { title: "优势树种", key: "dominant_tree_species", align: 'center', ellipsisTooltip: true, },
  { title: "起源", key: "origin", align: 'center' },
  { title: "年龄组", key: "age_group", align: 'center' },
  { title: "面积(ha)", key: "area", align: 'center', },
  { title: "蓄积(m³)", key: "stock", align: 'center', },
  { title: "蓄积(m³/ha)", key: "stock_per_ha", align: 'center' },
  { title: "平均树高(m)", key: "mean_tree_height", align: 'center' },
  { title: "平均胸径(cm)", key: "mean_dbh", align: 'center' },
  { title: "林分生物量", key: "forest_stand_biomass", align: 'center', },
  { title: "系数", key: "coefficient", align: 'center' },
  { title: "备注", key: "remark", ellipsisTooltip: true, hide: true, },
]);

</script>

<style scoped></style>